/*
# Rouleur Log - A log for cyclists.
# Copyright (C) 2006  Edward Copony (ecopony@gmail.com)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package com.blazingredfireball.rouleurlog.ria.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.blazingredfireball.rouleurlog.ria.business.UserDelegate;
	import com.blazingredfireball.rouleurlog.ria.event.LoginEvent;
	import com.blazingredfireball.rouleurlog.ria.model.RouleurlogModelLocator;
	import com.blazingredfireball.rouleurlog.ria.util.ViewUtil;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;

	public class LoginCommand implements ICommand, IResponder
	{
		private var model : RouleurlogModelLocator = RouleurlogModelLocator.getInstance();
		
		public function execute(event : CairngormEvent) : void
		{
			var delegate : UserDelegate = new UserDelegate( this );    
			var loginEvent : LoginEvent = LoginEvent( event );
			delegate.loginUser(loginEvent.username, loginEvent.password);
		}
		
		public function result(data : Object) : void
		{
			if (data.result)
			{
				model.user = data.result;
				// If this is the users first time logging in and they have not changed the
				// theme preferences model.user.theme will be null.
				// Check for this and if so use the model.theme property which is set to silver
				// on initialization
				if (model.user.theme != null) {
					ViewUtil.loadTheme(model.user.theme);
				} else {
					ViewUtil.loadTheme(model.theme);
				}
				
				model.viewState = RouleurlogModelLocator.MANAGE_RIDES_VIEW;
			}
			else
			{
				Alert.show( "Login Failed!" );
			}		
		}
		
		public function fault(info : Object) : void
		{
			var faultEvent : FaultEvent = FaultEvent( info );
			Alert.show("Login Failed!");
		}
		
	}
}